package com.example.runnable;

import com.example.thread.InsertTask;
import com.example.utils.TextFileReader;
import com.example.utils.ThreadPoolUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.example.runnable.Constants.W_PATH;

@Component
@ConditionalOnProperty(name = "run-env",havingValue = "test03thread")
public class Test03ThreadPool implements ApplicationRunner {

    @Resource
    HikariDataSource hikariDataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Connection connection = hikariDataSource.getConnection();
        connection.setAutoCommit(false);
        Statement statement = connection.createStatement();
        long begin=System.currentTimeMillis();
        TextFileReader fileReader = null;
        try {
            fileReader = new TextFileReader(W_PATH,"utf-8");
            List<String> list=null;
            AtomicInteger i=new AtomicInteger(1);
            while (fileReader.hasNext()){
                ThreadPoolUtils.executor.execute(new InsertTask(fileReader.readNextLines(200),i,begin,hikariDataSource));
            }
            System.out.println("总耗时:"+(System.currentTimeMillis()-begin));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileReader!=null){
                fileReader.close();
            }
            hikariDataSource.evictConnection(connection);
        }
    }
}
